<template>
  <el-dialog v-model="loginVisible" width="380px" :show-close="true">
    <template #header>
      <div class="text-xl font-bold text-center">登录 / 注册</div>
    </template>

    <el-tabs v-model="activeTab" class="login-tabs">
      <el-tab-pane label="密码登录" name="password">
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          label-width="0"
          size="large"
          class="mt-6"
        >
          <el-form-item prop="phonenumber">
            <el-input
              v-model="loginForm.phonenumber"
              placeholder="请输入手机号"
              clearable
            >
              <template #prefix>
                <i class="i-carbon-phone text-lg"></i>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              show-password
            >
              <template #prefix>
                <i class="i-carbon-locked text-lg"></i>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              class="w-full login-button"
              :loading="loading"
              @click="handleLogin"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="快速注册" name="register">
        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          label-width="0"
          size="large"
          class="mt-6"
        >
          <el-form-item prop="phonenumber">
            <el-input
              v-model="registerForm.phonenumber"
              placeholder="请输入手机号"
              clearable
            >
              <template #prefix>
                <i class="i-carbon-phone text-lg"></i>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码（6-20位）"
              show-password
            >
              <template #prefix>
                <i class="i-carbon-locked text-lg"></i>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请确认密码"
              show-password
            >
              <template #prefix>
                <i class="i-carbon-locked text-lg"></i>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="nickName">
            <el-input
              v-model="registerForm.nickName"
              placeholder="请输入昵称（选填）"
              clearable
            >
              <template #prefix>
                <i class="i-carbon-user text-lg"></i>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              class="w-full login-button"
              :loading="loading"
              @click="handleRegister"
            >
              注册
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <div class="text-center text-sm text-gray-400 mt-4 pt-4 border-t border-gray-700">
      <el-checkbox v-model="agreed" class="text-xs">
        <span class="text-gray-400">
          我已阅读并同意
          <NuxtLink to="/protocol" class="text-green-400 hover:text-green-300">《用户协议》</NuxtLink>
          和
          <NuxtLink to="/policies" class="text-green-400 hover:text-green-300">《隐私政策》</NuxtLink>
        </span>
      </el-checkbox>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'

const loginVisible = useLoginVisible()
const userStore = useUserStore()  // 使用Pinia store

const activeTab = ref('password')
const loading = ref(false)
const agreed = ref(false)

// 登录表单
const loginFormRef = ref<FormInstance>()
const loginForm = ref({
  phonenumber: '',
  password: ''
})

const validatePhone = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入手机号'))
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const loginRules: FormRules = {
  phonenumber: [{ validator: validatePhone, trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 注册表单
const registerFormRef = ref<FormInstance>()
const registerForm = ref({
  phonenumber: '',
  password: '',
  confirmPassword: '',
  nickName: ''
})

const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请确认密码'))
  } else if (value !== registerForm.value.password) {
    callback(new Error('两次密码输入不一致'))
  } else {
    callback()
  }
}

const registerRules: FormRules = {
  phonenumber: [{ validator: validatePhone, trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' }
  ],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }]
}

// 登录
const handleLogin = async () => {
  if (!agreed.value) {
    ElMessage.warning('请先阅读并同意用户协议和隐私政策')
    return
  }

  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const result = await userStore.login({
          username: loginForm.value.phonenumber,
          password: loginForm.value.password
        })

        if (result.success) {
          ElMessage.success('登录成功')
          loginVisible.value = false
          // 刷新页面以更新用户状态
          setTimeout(() => {
            window.location.reload()
          }, 500)
        } else {
          ElMessage.error(result.msg || '登录失败')
        }
      } finally {
        loading.value = false
      }
    }
  })
}

// 注册
const handleRegister = async () => {
  if (!agreed.value) {
    ElMessage.warning('请先阅读并同意用户协议和隐私政策')
    return
  }

  if (!registerFormRef.value) return

  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const result = await userStore.register({
          phonenumber: registerForm.value.phonenumber,
          password: registerForm.value.password,
          nickName: registerForm.value.nickName || registerForm.value.phonenumber
        })

        if (result.success) {
          ElMessage.success('注册成功，请登录')
          activeTab.value = 'password'
          loginForm.value.phonenumber = registerForm.value.phonenumber
          loginForm.value.password = ''
          registerForm.value = {
            phonenumber: '',
            password: '',
            confirmPassword: '',
            nickName: ''
          }
        } else {
          ElMessage.error(result.msg || '注册失败')
        }
      } finally {
        loading.value = false
      }
    }
  })
}

// 监听路由变化，关闭弹窗
watch(() => useRoute().path, () => {
  loginVisible.value = false
})
</script>

<style scoped lang="scss">
// 强制深色主题对话框
:deep(.el-dialog) {
  background: #1c1d1f !important;
  border-radius: 16px;
  color: #fff;
}

:deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  margin: 0;
  background: #1c1d1f !important;

  .el-dialog__title {
    color: #fff !important;
  }
}

:deep(.el-dialog__body) {
  padding: 10px 30px 30px;
  background: #1c1d1f !important;
}

// 标签页样式
.login-tabs {
  :deep(.el-tabs__header) {
    background: transparent;
  }

  :deep(.el-tabs__item) {
    color: rgba(255, 255, 255, 0.6) !important;
    font-size: 15px;

    &.is-active {
      color: #fff !important;
    }

    &:hover {
      color: rgba(255, 255, 255, 0.8) !important;
    }
  }

  :deep(.el-tabs__active-bar) {
    background: #00f48e !important;
    height: 3px;
    border-radius: 2px;
  }

  :deep(.el-tabs__nav-wrap::after) {
    background: rgba(255, 255, 255, 0.1) !important;
  }
}

// 输入框样式 - 深色背景+白色文字
:deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.08) !important;
  box-shadow: none !important;
  border: 1px solid rgba(255, 255, 255, 0.15) !important;

  &:hover {
    border-color: rgba(255, 255, 255, 0.25) !important;
  }

  &.is-focus {
    border-color: #00f48e !important;
    box-shadow: 0 0 0 1px rgba(0, 244, 142, 0.2) !important;
  }
}

:deep(.el-input__inner) {
  color: #fff !important;
  background: transparent !important;

  &::placeholder {
    color: rgba(255, 255, 255, 0.4) !important;
  }
}

// 输入框前缀图标
:deep(.el-input__prefix) {
  color: rgba(255, 255, 255, 0.6) !important;
}

// 显示密码图标
:deep(.el-input__suffix) {
  .el-input__icon {
    color: rgba(255, 255, 255, 0.6) !important;
  }
}

// 登录按钮
.login-button {
  background: linear-gradient(90deg, #00a8e6, #00b84d 50%, #00b84d) !important;
  border: none;
  border-radius: 24px;
  height: 44px;
  font-size: 16px;
  font-weight: 600;
  color: #fff !important;

  &:hover {
    opacity: 0.9;
  }
}

// 复选框样式
:deep(.el-checkbox__label) {
  color: rgba(255, 255, 255, 0.7) !important;
  font-size: 12px;
}

:deep(.el-checkbox__inner) {
  background: rgba(255, 255, 255, 0.1) !important;
  border-color: rgba(255, 255, 255, 0.3) !important;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background: #00f48e !important;
  border-color: #00f48e !important;
}

// 链接文字
:deep(a) {
  color: #00f48e !important;

  &:hover {
    color: #00d67d !important;
  }
}

// 底部文字
.text-gray-400 {
  color: rgba(255, 255, 255, 0.6) !important;
}
</style>

<!-- 全局样式（Dialog挂载到body，需要非scoped样式） -->
<style lang="scss">
// 登录对话框深色主题（全局生效）
.el-dialog {
  background: #1c1d1f !important;
  border-radius: 16px;

  .el-dialog__header {
    background: #1c1d1f !important;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    .el-dialog__title {
      color: #fff !important;
    }

    .el-dialog__close {
      color: rgba(255, 255, 255, 0.6) !important;

      &:hover {
        color: #fff !important;
      }
    }
  }

  .el-dialog__body {
    background: #1c1d1f !important;
  }
}
</style>
